package com.ycl2.imports.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.read.metadata.ReadSheet;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.ycl2.imports.entity.BaseImportTask;
import com.ycl2.imports.entity.BaseImportTaskHeader;
import com.ycl2.imports.entity.Importexcel;
import com.ycl2.imports.lisner.EasyExcelImport;
import com.ycl2.imports.mapper.BaseImportTaskHeaderMapper;
import com.ycl2.imports.mapper.BaseImportTaskMapper;
import com.ycl2.imports.service.IBaseImportTaskHeaderService;
import com.ycl2.imports.service.impl.BaseImportTaskHeaderServiceImpl;
import com.ycl2.imports.service.impl.BaseImportTaskServiceImpl;
import com.ycl2.imports.service.impl.ImportexcelServiceImpl;
import com.zbf.common.entity.ResponseResult;
import com.zbf.common.utils.ZipMultiFile;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 袁成龙
 * @since 2020-10-20
 */
@RestController
@RequestMapping("/importexcel")
public class ImportexcelController implements SimpleJob {

    static int t = 0;
    static Integer ss=0;
    static String filenames = "";

    @Autowired
    private ImportexcelServiceImpl importexcelService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MinioDemoController minioDemoController;

    private static final Logger LOGGER = LoggerFactory.getLogger(ImportexcelController.class);

     ResponseResult responseResult = new ResponseResult();

    @Autowired
    private BaseImportTaskHeaderMapper baseImportTaskHeaderMapper;

    @Autowired
    private BaseImportTaskMapper baseImportTaskHeader;

    Map<String,Object> map=new HashMap<>();


    @Autowired
    private BaseImportTaskServiceImpl baseImportTaskService;

    @Autowired
    private BaseImportTaskHeaderServiceImpl iBaseImportTaskHeaderService;

    MultipartFile file;

    int i=0;
    @RequestMapping("upload")
    public ResponseResult upload(String zhi,String imname) throws IOException {
        BaseImportTask baseImportTask = new BaseImportTask(null,1,imname,0,4,0, LocalDateTime.now(),null);
        boolean save1 = baseImportTaskService.save(baseImportTask);
        String[] split = zhi.split(",");
        boolean save = false;
        if(save1){
            for (String str:split) {
                filenames+=str+",";
                if(!str.equals("")){
                    int maxid1 = baseImportTaskHeader.maxid();
                //    int maxid = maxid1.getId();
                    BaseImportTaskHeader baseImportTaskHeader = new BaseImportTaskHeader(1, 0, "I:\\getExec\\" + str, 0, 0,i,maxid1);
                    save = iBaseImportTaskHeaderService.save(baseImportTaskHeader);
                }
                i++;
            }
        }
        if(save){
            responseResult.setCode(1006);
        }else{
            responseResult.setCode(1004);
        }
        return responseResult;
    }


    @SneakyThrows
    @Override
    public void execute(ShardingContext shardingContext) {

        System.out.println("-------分片执行导入--------");

        //List<BaseImportTask> list1 = baseImportTaskService.list();
        /*List<BaseImportTaskHeader> list = list1;*/
       // System.out.println("数据获取==="+list1.size());
        //获取分片的总数
        int shardingTotalCount = shardingContext.getShardingTotalCount();
        //获取分片项
        int shardingItem = shardingContext.getShardingItem();

        List<BaseImportTask> task = baseImportTaskHeader.task();
        for (BaseImportTask ba:task) {
            for (int j = 0; j < ba.getTaskNum(); j++) {
                QueryWrapper queryWrapper = new QueryWrapper();
                queryWrapper.eq("pid",ba.getId());
                List<BaseImportTaskHeader> list = iBaseImportTaskHeaderService.list(queryWrapper);
                //System.out.println(list.get(i).getPath());
                if (j== shardingItem) {
                Integer pid = ba.getId();
                ss = pid;
                long start = System.currentTimeMillis();
                String fileName = list.get(j).getPath();
                // filenames+=fileName+",";
                System.out.println("文件名1" + fileName);
                ExcelReader excelReader = EasyExcel.read(fileName, Importexcel.class, new EasyExcelImport(importexcelService, rabbitTemplate)).build();
                ReadSheet readSheet = EasyExcel.readSheet(0).build();
                excelReader.read(readSheet);
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
                long end = System.currentTimeMillis();
                System.out.println("分片"+j+"==========" + (end - start) / 1000.0);
                    System.out.println("投表id==="+ba.getId());
                int updateokstatus = baseImportTaskHeaderMapper.updateokstatus(ba.getId(),fileName);
                System.out.println("----一" + updateokstatus);
                if (updateokstatus == 1) {
                    t += updateokstatus;
                }
                System.out.println(t);
                break;
            } else if (j == shardingItem) {

                long start = System.currentTimeMillis();
                String fileName =list.get(j).getPath();
                // filenames+=fileName+",";
                System.out.println("文件名2" + fileName);
                ExcelReader excelReader = EasyExcel.read(fileName, Importexcel.class, new EasyExcelImport(importexcelService, rabbitTemplate)).build();
                ReadSheet readSheet = EasyExcel.readSheet(0).build();
                excelReader.read(readSheet);
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
                long end = System.currentTimeMillis();
                System.out.println("分片"+j+"==========" + (end - start) / 1000.0);
                    System.out.println("-----投表id==="+ba.getId());
                int updateokstatus = baseImportTaskHeaderMapper.updateokstatus(ba.getId(),fileName);
                System.out.println("----二" + updateokstatus);
                if (updateokstatus == 1) {
                    t += updateokstatus;
                }
                break;
            } else if (j == shardingItem) {
                long start = System.currentTimeMillis();
                String fileName =list.get(j).getPath();
                //filenames+=fileName+",";
                System.out.println("文件名3" + fileName);
                ExcelReader excelReader = EasyExcel.read(fileName, Importexcel.class, new EasyExcelImport(importexcelService, rabbitTemplate)).build();
                ReadSheet readSheet = EasyExcel.readSheet(0).build();
                excelReader.read(readSheet);
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
                long end = System.currentTimeMillis();
                System.out.println("分片"+j+"==========" + (end - start) / 1000.0);
                    System.out.println("投表id==="+ba.getId());
                int updateokstatus = baseImportTaskHeaderMapper.updateokstatus(ba.getId(),fileName);
                System.out.println("----三" + updateokstatus);
                if (updateokstatus == 1) {
                    t += updateokstatus;
                }
                break;
            } else if (j == shardingItem) {
                long start = System.currentTimeMillis();

                String fileName = list.get(j).getPath();
                // filenames+=fileName+",";
                System.out.println("文件名4" + fileName);
                ExcelReader excelReader = EasyExcel.read(fileName, Importexcel.class, new EasyExcelImport(importexcelService, rabbitTemplate)).build();
                ReadSheet readSheet = EasyExcel.readSheet(0).build();
                excelReader.read(readSheet);
                // 这里千万别忘记关闭，读的时候会创建临时文件，到时磁盘会崩的
                excelReader.finish();
                long end = System.currentTimeMillis();
                    System.out.println("投表id==="+ba.getId());
                int updateokstatus = baseImportTaskHeaderMapper.updateokstatus(ba.getId(),fileName);
                System.out.println("----四" + updateokstatus);
                if (updateokstatus == 1) {
                    t += updateokstatus;
                }
                System.out.println("分片"+j+"==========" + (end - start) / 1000.0);
                break;
            }

            }
        }

        System.out.println("======"+t);


        if(t==4){
            Thread.sleep(3000);
            map.put("isOk",1);
            String string = JSON.toJSONString(map);
            rabbitTemplate.convertAndSend("T-Exchange1","",string);
            String substring1 = filenames.substring(0, filenames.length() - 1);
            String[] split = substring1.split(",");
            baseImportTaskHeader.updateimporttask(ss);
            File[] srcFiles = {new File("I:\\getExec\\"+split[0]),
                    new File("I:\\getExec\\"+split[1]),
                    new File("I:\\getExec\\"+split[2]),
                    new File("I:\\getExec\\"+split[3])};
            String s = split[0];
            String substring = s.substring(0, 1);
            File zipFile1 = new File("I:\\getExec\\"+substring+".zip");
            ZipMultiFile.zipFiles(srcFiles,zipFile1);


            File file = new File("I:\\getExec\\"+substring+".zip");
            InputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile =new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(inputStream));
            String upload = minioDemoController.upload(multipartFile);
            if(upload!=null&&!"null".equals(upload)){
                int i = baseImportTaskHeader.updateminioPath(upload, ss);
                String str = "I:\\getExec\\"+substring+".zip";
                System.out.println("我的输出一下=="+str);
                File ff = new File(str);
                boolean delete = ff.delete();
                System.out.println("也不知道成功了没=="+delete);
            }
            t = 0;
            ss=0;
            filenames = "";
        }
    }
}

